package Pet.Management.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.SecretKey;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.nio.charset.StandardCharsets;

@Component
public class JwtUtils {
    
    private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);

    @Value("${jwt.secret:your-secret-key-must-be-at-least-32-bytes-long}")
    private String secret;

    @Value("${jwt.expiration:86400}")
    private Long expiration;

    private SecretKey getSecretKey() {
        // 确保密钥长度足够（至少256位/32字节）
        byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
        logger.debug("使用密钥长度: {} 字节", keyBytes.length);
        return Keys.hmacShaKeyFor(keyBytes);
    }

    public String generateToken(String username, Long userId) {
        try {
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", userId);
            
            Instant now = Instant.now();
            Instant expiryDate = now.plus(expiration, ChronoUnit.SECONDS);
    
            return Jwts.builder()
                    .claims(claims)
                    .subject(username)
                    .issuedAt(Date.from(now))
                    .expiration(Date.from(expiryDate))
                    .signWith(getSecretKey())
                    .compact();
        } catch (Exception e) {
            logger.error("生成Token失败", e);
            throw new RuntimeException("生成Token失败", e);
        }
    }

    public Claims parseToken(String token) {
        try {
            return Jwts.parser()
                    .verifyWith(getSecretKey())
                    .build()
                    .parseSignedClaims(token)
                    .getPayload();
        } catch (Exception e) {
            logger.error("解析Token失败", e);
            throw new RuntimeException("解析Token失败", e);
        }
    }

    public boolean validateToken(String token) {
        try {
            Jwts.parser()
                .verifyWith(getSecretKey())
                .build()
                .parseSignedClaims(token);
            return true;
        } catch (Exception e) {
            logger.warn("Token验证失败: {}", e.getMessage());
            return false;
        }
    }

    public String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    public Long getUserIdFromToken(String token) {
        Claims claims = parseToken(token);
        return Long.parseLong(claims.get("userId").toString());
    }
} 